<template>
  <!-- 增加、编辑商城客户 -->
  <el-dialog :title="dialogTitle" :visible.sync="showDialog_" top="0%" custom-class='dialog_right dialogScroll_add MkAddPropertyCustomer' @open="openDialog" @close="closeDialog('addForm')">
    <el-scrollbar :wrapStyle="[{maxHeight:(bodyHeight - 200)+'px'}]">
      <el-form :model="addForm.formItem" :rules="addForm.rules" ref="addForm" label-width="110px">

        <h5>基本信息</h5>
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model='addForm.formItem.customerName' placeholder="请输入客户名称（必填）">
          </el-input>
        </el-form-item>
        <el-form-item label="票据抬头" prop="billHeader">
          <el-input v-model='addForm.formItem.billHeader' placeholder="请输入票据抬头（必填）">
          </el-input>
        </el-form-item>
        <el-form-item label="社会信用代码" prop="creditCode">
          <el-input v-model='addForm.formItem.creditCode' placeholder="请输入社会信用代码（必填）">
          </el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="contact">
          <el-input v-model='addForm.formItem.contact' placeholder="请输入联系人（必填）">
          </el-input>
        </el-form-item>
        <el-form-item label="联系人电话" prop="contactPhone">
          <el-input v-model='addForm.formItem.contactPhone' placeholder="请输入联系人电话（必填）">
          </el-input>
        </el-form-item>

        <h5>社区信息</h5>
        <el-form-item label="社区名称" prop="communityName">
          <el-input v-model='addForm.formItem.communityName'  :maxlength="40" placeholder="请输入社区名称（必填）">
          </el-input>
        </el-form-item>
        <el-form-item label="物业名称" prop="propertyName">
          <el-input v-model='addForm.formItem.propertyName'  :maxlength="40" placeholder="请输入物业名称（必填）">
          </el-input>
        </el-form-item>
        <el-form-item label="有效日期" prop="expireTime_">
          <el-date-picker
            v-model="addForm.formItem.expireTime_"
            type="date"
            placeholder="请选择有效日期（必选）">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="所在城市" prop="siteCityId">
          <el-select v-model.number="addForm.formItem.siteCityId" placeholder="请选择城市（必选）" @change="changeCity">
            <el-option v-for="item in cityArr" :label="item.name" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务站点" prop="siteId">
          <el-select v-model.number="addForm.formItem.siteId"  placeholder="请选择服务站点（必选）">
            <el-option v-for="item in siteArr" :label="item.name" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-form-item>

        <h5>管理员信息</h5>
        <el-form-item label="超级管理员" prop="adminName">
          <el-input v-model='addForm.formItem.adminName' placeholder="请输入超级管理员（必填）">
          </el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model='addForm.formItem.idCard' placeholder="请输入身份证号（必填）">
          </el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="adminPhone">
          <el-input v-model='addForm.formItem.adminPhone' placeholder="请输入联系电话（必填）">
          </el-input>
        </el-form-item>
        <template v-if="!currentCustomer">
          <el-form-item label="登录密码" prop="password">
            <el-input v-model='addForm.formItem.password' type="password" placeholder="请输入登录密码（必填）">
            </el-input>
          </el-form-item>
        </template>

        <el-form-item label="支付Key" prop="payKey">
          <el-input v-model.trim='addForm.formItem.payKey' :maxlength="50" placeholder="请输入支付Key（必填）">
          </el-input>
        </el-form-item>
        <el-form-item label="支付密钥" prop="paySecret">
          <el-input v-model.trim='addForm.formItem.paySecret' :maxlength="50"  placeholder="请输入支付密钥（必填）">
          </el-input>
        </el-form-item>
      </el-form>
    </el-scrollbar>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" class="btn-primary"  :disabled = "isSubmitBtnDisabled" @click="submitForm('addForm')" v-loading.fullscreen.lock="fullscreenLoading">提交</el-button>
      <el-button type='primary' class="btn-cancel" @click="showDialog_=false">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import customerService from '../../../services/customer'
import {mapState} from 'vuex'
export default {
  name: 'MkAddPropertyCustomer',
  props: ['showDialog','currentCustomer'],
  computed:mapState({
    bodyHeight: state => state.global.bodyHeight
  }),
  watch: {
    showDialog: function(value) {
      this.showDialog_ = value;
    },
  },
  mounted: function() {

  },
  methods: {
    changeCity(val) {
      if(val) {
        this.searchSiteCondition.id = val;
        if(this.currentCustomer && this.currentCustomer.siteCityId == val) {
          this.searchSiteCondition.proId = this.currentCustomer.id;
        }else{
          this.searchSiteCondition.proId = '';
        }

        customerService.loadSiteByCityServer(this.searchSiteCondition,data=>{
           this.siteArr = data.data;
//           if(this.currentCustomer && this.isFirst){//编辑时，将第一次将信息导入下拉框
//             this.isFirst = false;
//             this.addForm.formItem.siteId = this.currentCustomer.siteId;
//           }else{
             this.addForm.formItem.siteId = '';
//           }

        })
      }
    },
    loadCities() {
      customerService.loadCitiesInPropertyCustomerServer(data=>{
        this.cityArr = data.data;
        if(this.currentCustomer) {
          this.addForm.formItem.siteCityId = this.currentCustomer.siteCityId;

          this.searchSiteCondition.id = this.currentCustomer.siteCityId;
          this.searchSiteCondition.proId = this.currentCustomer.id;
          customerService.loadSiteByCityServer(this.searchSiteCondition,data=>{
            this.siteArr = data.data;
//            if(this.currentCustomer && this.isFirst){//编辑时，将第一次将信息导入下拉框
//              this.isFirst = false;
              this.addForm.formItem.siteId = this.currentCustomer.siteId;
//            }else{
//              this.addForm.formItem.siteId = '';
//            }

          })

        }
//        if(this.currentCustomer && this.currentCustomer.siteCityId == val) {
//          this.searchSiteCondition.proId = this.currentCustomer.id;
//        }else{
//          this.searchSiteCondition.proId = '';
//        }
//        if() {
//          this.searchSiteCondition.id = this.currentCustomer.siteCityId;
//          customerService.loadSiteByCityServer(this.searchSiteCondition,data=>{
//            this.siteArr = data.data;
//            if(this.currentCustomer && this.isFirst){//编辑时，将第一次将信息导入下拉框
//              this.isFirst = false;
//              this.addForm.formItem.siteId = this.currentCustomer.siteId;
//            }else{
//              this.addForm.formItem.siteId = '';
//            }
//
//          })
//        }
      })
    },
    openDialog() {
      this.isRefresh = false;
      this.isSubmitBtnDisabled = false;
      this.loadCities();
      let currentCustomer = this.currentCustomer;
      let form  = this.addForm.formItem;
      if(currentCustomer) {
        this.dialogTitle = '编辑客户';
        this.isFirst = true;
        form.adminName = currentCustomer.adminName;
        form.adminPhone = currentCustomer.adminPhone;
        form.billHeader = currentCustomer.billHeader;
        form.communityName = currentCustomer.communityName;
        form.contact = currentCustomer.contact;
        form.contactPhone = currentCustomer.contactPhone;
        form.creditCode = currentCustomer.creditCode;
        form.customerName = currentCustomer.customerName;
        form.idCard = currentCustomer.idCard;
        form.password = currentCustomer.password;
        form.propertyName = currentCustomer.propertyName;
        if(currentCustomer.expireDate !=='已过期'){
          form.expireTime_ = currentCustomer.expireDate;
        }
        form.payKey = currentCustomer.payKey;
        form.paySecret = currentCustomer.paySecret;
        form.id = currentCustomer.id;
      }
    },
    closeDialog(formName) {
      this.$refs[formName].resetFields();
      let form = this.addForm.formItem;
      for(let i in form) {
          form[i] = '';
      }
      this.$emit('closeDialog',this.isRefresh);
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid=>{
        if(valid) {
          this.fullscreenLoading = true;
          this.isSubmitBtnDisabled = true;
          let form = this.addForm.formItem;
          let params = {
            adminName: form.adminName,
            adminPhone: form.adminPhone,
            billHeader: form.billHeader,
            communityName:form.communityName,
            contact: form.contact,
            contactPhone: form.contactPhone,
            creditCode: form.creditCode,
            customerName: form.customerName,
            idCard: form.idCard,
            password: form.password,
            propertyName: form.propertyName,
            siteCityId: form.siteCityId,
            siteId: form.siteId,
            payKey: form.payKey,
            paySecret:form.paySecret,
            expireTime: new Date(form.expireTime_).pattern('yyyy-MM-dd')
          }

          if(this.currentCustomer){
              params.id = form.id;
            customerService.editPropertyCustomerServer(params,data=>{
              this.$message.success('编辑成功');
              this.isRefresh = true;
              this.showDialog_ = false;
              this.fullscreenLoading = false;
            },data=>{
              this.fullscreenLoading = false;
              this.isSubmitBtnDisabled = false;
            })
          }else{
            customerService.addPropertyCustomerServer(params,data=>{
              this.$message.success('新增成功');
              this.isRefresh = true;
              this.showDialog_ = false;
              this.fullscreenLoading = false;
            },data=>{
              this.fullscreenLoading = false;
              this.isSubmitBtnDisabled = false;
            })
          }
        }
      })
    },
  },

  data() {
    let checkName = (rule, value, callback) => {
      if (value) {
        let reg = new RegExp("[A-Za-z\u4e00-\u9fa5]");
        if (!reg.test(value)) {
          callback(new Error('请输入含有中文或英文的客户名称'));
        } else if (value.length > 40) {
          callback(new Error('请输入不超过40个字符的客户名称'))
        } else {
          callback();
        }
      } else {
        callback(new Error('请输入客户名称'));
      }
    };
    let checkBillHeader = (rule, value, callback) => {
      if (value) {
        let reg = new RegExp("[A-Za-z\u4e00-\u9fa5]");
        if (!reg.test(value)) {
          callback(new Error('请输入含有中文或英文的发票抬头'));
        } else if (value.length > 40) {
          callback(new Error('请输入不超过40个字符的发票抬头'))
        } else {
          callback();
        }
      } else {
        callback(new Error('请输入发票抬头'));
      }
    };
    let checkCreditCode = (rule, value, callback) => {
      if (value) {
        if (value.length > 40) {
          callback(new Error('请输入不超过40个字符的社会信用代码'))
        } else {
          callback();
        }
      } else {
        callback(new Error('请输入社会信用代码'));
      }
    };
    let checkContact = (rule, value, callback) => {
      if (value) {
        let reg = new RegExp("[A-Za-z\u4e00-\u9fa5]");
        if (!reg.test(value)) {
          callback(new Error('请输入含有中文或英文的联系人'));
        } else if (value.length > 40) {
          callback(new Error('请输入不超过40个字符的联系人'))
        } else {
          callback();
        }
      } else {
        callback(new Error('请输入联系人'));
      }
    };
    let checkAdminName = (rule, value, callback) => {
      if (value) {
        let reg = new RegExp("[A-Za-z\u4e00-\u9fa5]");
        if (!reg.test(value)) {
          callback(new Error('请输入含有中文或英文的超级管理员'));
        } else if (value.length > 40) {
          callback(new Error('请输入不超过40个字符的超级管理员'))
        } else {
          callback();
        }
      } else {
        callback(new Error('请输入超级管理员'));
      }
    };
    let checkAdminIdCard = (rule, value, callback) => {
      if (value) {
        value = value.replace(/(^\s+)|(\s+$)/g, "");
        if (value.length != 18 && value.length != 15) {
          callback(new Error('请输入正确长度的身份证号'));
        } else {
          callback();
        }
      } else {
        callback(new Error('请输入身份证号'));
      }
    };
    let checkAdminPhone = (rule, value, callback) => {
      if (value) {
        let reg = new RegExp("^1(3|4|7|5|8)([0-9]{9})");
        if (!reg.test(value)) {
          callback(new Error('请输入正确格式的手机号'));
        } else {
          callback();
        }
      } else {
        callback(new Error('请输入联系电话'));
      }
    };
    let checkContactPhone = (rule, value, callback) => {
      if (value) {
        let reg = new RegExp("(^400[0-9]{7})|(^1(3|4|7|5|8)([0-9]{9}))|(^0[0-9]{2,3}-[0-9]{7,8})");
        if (!reg.test(value)) {
          callback(new Error('请输入正确格式的联系人电话'));
        } else {
          callback();
        }
      } else {
        callback(new Error('请输入联系人电话'));
      }
    };
    let checkPassword = (rule, value, callback) => {
      if (value) {
        if (value.length > 18 || value.length < 6) {
          callback(new Error('请输入6-18个字符的登录密码'))
        } else {
          callback();
        }
      } else {
        callback(new Error('请输入登录密码'));
      }
    };
    let checkPropertyName = (rule, value, callback) => {
      if (value.trim() == '') {
        callback(new Error('请输入物业名称'));
      }else {
        if(value.length>40) {
           callback(new Error('最多输入40个字符'));
       }else{
           callback();
       }
      }
    };
    let checkCommunityName = (rule, value, callback) => {
      if (value.trim() == '') {
        callback(new Error('请输入社区名称'));
      }else {
        if(value.length>40) {
          callback(new Error('最多输入40个字符'));
        }else{
          callback();
        }
      }
    };
    return {
      searchSiteCondition:{
        id: '',
        proId: ''
      },
      isFirst: true,
      isSubmitBtnDisabled: false,
      fullscreenLoading: false,
      siteArr: [],
      cityArr: [],
      isRefresh: false,
      showDialog_: this.showDialog,
      dialogTitle: '新增客户',
      addForm: {
        formItem: {
          adminName: '',
          adminPhone: '',
          billHeader: '',
          communityName: '',
          contact: '',
          contactPhone: '',
          creditCode: '',
          customerName: '',
          idCard: '',
          password: '',
          propertyName: '',
          siteCityId: '',
          siteId: '',
          id:'',
          payKey:'',
          paySecret:'',

          expireTime_: '',
        },
        rules: {
          payKey: [
            {required:true,message:'支付Key不能为空', trigger: 'change,blur'},
            {max: 50, message: '最大长度为50', trigger: 'change,blur' }
          ],
          paySecret:  [
            {required:true,message:'支付密钥不能为空', trigger: 'change,blur'},
            {max: 50, message: '最大长度为50', trigger: 'change,blur' }
          ],
          expireTime_:{required: true,message:'请选择有效日期',trigger:'change,blur'},
          adminName:{ validator: checkAdminName ,trigger:'change'},
          adminPhone:{ validator: checkAdminPhone, trigger: 'change' },
          billHeader:{ validator: checkBillHeader ,trigger:'change'},
          communityName:{ validator: checkCommunityName ,trigger:'change'},
          contact:  { validator: checkContact ,trigger:'change'},
          contactPhone:{ validator: checkContactPhone, trigger: 'change' },
          creditCode: { validator: checkCreditCode ,trigger:'change'},
          customerName: { validator: checkName ,trigger: 'change' },
          idCard: { validator: checkAdminIdCard, trigger: 'change' },
          password: { validator: checkPassword , trigger: 'change'},
          propertyName: { validator: checkPropertyName , trigger: 'change'},
          siteCityId:{required:true,message:'请选择所在城市',type:'number',trigger:'change'},
          siteId: {required:true,message:'请选择站点',type:'number',trigger:'change'}
        }
      },
    }
  }
}

</script>

<style lang="less">
@import '../../../assets/style/main.less';
.MkAddPropertyCustomer {
  h5 {
    font-size: 18px;
    font-weight: normal;
    color: @fontColorOne;
    padding: 20px 0;
  }
  h5:first-child {
    padding-top: 0;
  }
}
</style>
